package com.syg.servlet03;

import com.syg.toolkit.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;

/**
 * 通过request对象获取客户端请求头信息
 * 　getHeader(string name)方法:String
 * 　getHeaders(String name)方法:Enumeration
 * 　getHeaderNames()方法
 */
@WebServlet("/reqHeader")
public class _07_Request_Header extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
        //通过设置响应头控制浏览器以UTF-8的编码显示数据
        resp.setHeader("content-type","text/html;charset=utf-8");//等价于：resp.setContentType("text/html;charset=utf-8");
        //获取输出流
        PrintWriter respOut = resp.getWriter();
        Enumeration<String> reqHeadInfos = req.getHeaderNames();//获取所有的请求头
        respOut.write("获取到客户端所有的请求头信息如下");
        respOut.write("<hr/>");
        while(reqHeadInfos.hasMoreElements()){
            String headName = reqHeadInfos.nextElement();
            String headValue = req.getHeader(headName);
            String paramStr = "请求头的名是==>"+headName;
            String formatStr = formatLength(paramStr,40,"_","1");
            respOut.write(formatStr+"\t,请求头对应的值是==>"+headValue);
            respOut.write("<br/>");
        }
    }

    /**
     *
     * @param str 原始数据
     * @param strLength 要扩展到的长度
     * @param padding 扩展填充字符
     * @param direction 扩展字符相对于obj插入的位置，0左边，1右边
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String formatLength(String str, int strLength,String padding, String direction) {
        int strLen = str.length();
        while (strLen<strLength){
            StringBuffer sb = new StringBuffer();
            if (Constants.zero.equals(direction)){
                sb.append(padding).append(str);
            }else{
                sb.append(str).append(padding);
            }
            str = sb.toString();
            strLen = str.length();
        }
        return str;
    }
}
